<?php
namespace Mapi\Controller;
use Mapi\Controller\BaseController;
require_once 'Qiniu/autoload.php';
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
use \Qiniu\Processing\PersistentFop;

class ArticleController extends BaseController {
	protected static $apiUrl = 'http://mobile.appwuhan.com/helper/';
	private $token = '';
	private $rotate = 0;

	public function createArticle() {
		if(IS_POST) {
			apigetpost();
			// $token = I('post.userToken'); // userToken
			// $token = '281c9830de5da1a4048ae9fe06f13673';

			// 获取当前用户所在频道	
			$channelres=M('UserInfo')->alias('ui')
				->join('__CHANNEL__ c on ui.userchannel=c.chid')
				->where(array('ui.uid' => $this->uid))->find();
			$userchannel =  $channelres['userchannel'];

			$dataGet['user_id'] = $this->uid;  // 用户ID
			$dataGet['title'] = I('post.title', ''); // 文稿标题
			$dataGet['author'] = I('post.author', ''); // 文稿作者
			$dataGet['content'] = I('post.content', ''); // 文稿内容
			$dataGet['create_time'] = time();
			$dataGet['update_time'] = time();

			$dataGet['column_id'] = $userchannel;
			if(I('post.hasAttchment')==1){ // 1-有附件   0-无附件，state字段的值为0
				$dataGet['state'] = -1;
			}elseif(I('post.hasAttchment')==0){ // 1-有附件   0-无附件，state字段的值为0
				$dataGet['state'] = 0;
			}
			$articleModel = D('Article');
			if($articleModel->create($dataGet)) {
				$res = $articleModel->add($dataGet);
				if($res) {
					$message['resultCode'] = 0;
					$message['message'] = '文档添加成功';
					$message['articleId'] = $res;		 // 文稿ID	

					/*消息推送*/
					if($dataGet['state']==0){
						$trans=json_encode(array('pushCode'=>100,'objectId'=>$res,'userId'=>0));
						$channelid = unserialize($channelres['relation']);
						$uidList = $channelid[0];
						foreach ($uidList as $key => $value) {
							if($value==$this->uid){
								unset($uidList[$key]);
							}
						}
						$authorName = $channelres['realname'];
						// \Think\Log::write(implode(',', $uidList),'uidList');
						sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=> $authorName . '提交稿件《' . $dataGet['title'] . '》，请审核！','trans'=>$trans));
					}

				} else {
					$message['resultCode'] = 1;
					$message['message'] = '文档添加失败';
				}
			} else {
				$message['resultCode'] = 1;
				$message['message'] = $articleModel->getError();
			}

			$this->ajaxReturn($message);
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '请求类型错误';
			$this->ajaxReturn($message);
		}
	}


	/**
	 * 更新附件所关联的文章ID
	 * @param  [type] $articleId [description]
	 * @param  [type] $attachId  [description]
	 * @return [type]            [description]
	 */
	public function updateAttachByAid($articleId, $attachId) {
		$res = M('Attachment')->where(array('attachid' => $attachId))->save(array('aid' => $articleId));
		return $res;
	}



	/**
	 * 更新附近的排列位置
	 * @return [type] [description]
	 */
	public function updateAttachSort() {
		apigetpost();
		$attId = intval(I('post.attId'));
		$sortId = I('post.sortId', 0);

		if(!$attId) {
			$message['resultCode'] = 1;
			$message['message'] = '附件ID未知';
			$this->ajaxReturn($message);
		}

		$res = M('Attachment')->where(array('attachid' => $attId))->save(array('sort' => $sortId));

		if($res !== false) {
			$message['resultCode'] = 0;
			$message['message'] = '更新成功';
			$this->ajaxReturn($message);
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '更新失败';
			$this->ajaxReturn($message);
		}
	}

	/**
	 * 删除已上传的附件列表
	 * @return [type] [description]
	 */
	public function delUploadedAttach() {
		apigetpost();
		$attIds = I('post.attIds');

		if(!$attIds) {
			$message['resultCode'] = 1;
			$message['message'] = '删除ID不能为空';
			$this->ajaxReturn($message);
		}

		$map['attachid'] = array('in', $attIds);
		$attachInfo = M('Attachment')->field('aid, filetype')->where($map)->find();
		$res = M('Attachment')->where($map)->save(array('aid' => 0));
		if($res != false) {
			$flashType = array('video/mp4', 'video/x-msvideo', 'video/quicktime');
			if(in_array($attachInfo['filetype'], $flashType)) {
				M('Article')->where(array('id' => $attachInfo['aid']))->save(array('is_video' => 0));
			}

			$message['resultCode'] = 0;
			$message['message'] = '更新成功';
			$this->ajaxReturn($message);
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '更新失败';
			$this->ajaxReturn($message);
		}

	}

	/**
	 * 更新上传稿件纪录
	 * @return [type] [description]
	 */
	public function updateArticheById() {
		apigetpost();
		$dataGet['articleId'] = intval(I('post.articleId'));
		$dataGet['title'] = I('post.title');
		$dataGet['content'] = I('post.content');
		$dataGet['author'] = I('post.author');
		$dataGet['create_time'] = time();
		$dataGet['update_time'] = time();

		if(!$dataGet['articleId']) {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}

		if(I('post.hasAttchment') == 1){ // 1-有附件   0-无附件，state字段的值为0
			$dataGet['state'] = -1;
		}elseif(I('post.hasAttchment') == 0){ // 1-有附件   0-无附件，state字段的值为0
			$dataGet['state'] = 0;
		}

		$map['id']=$dataGet['articleId'];
		$article=M('Article')
			->alias('ar')
			->join('__CHANNEL__ ch ON ar.column_id=ch.chid','left')
			->field("user_id createuserid,id articleId,state status,relation,title")
			->where($map)->find();

		if($article){
			$approve = unserialize($article['relation']);
			if($article['createuserid']==$this->uid ||  in_array($this->uid,$approve[0])){
				$res = M('Article')->where(array('id' => $dataGet['articleId']))->save($dataGet);

				if($res !== false) {
					/*文稿状态修改为待审核后消息推送*/
					if($dataGet['state'] == 0){

						$trans=json_encode(array('pushCode'=>100,'objectId'=>$dataGet['articleId'],'userId'=>0));
						$channelid = unserialize($article['relation']);
						$uidList = $channelid[0];
						foreach ($uidList as $key => $value) {
							if($value==$this->uid){
								unset($uidList[$key]);
							}
						}

						if($this->uid!=$article['createuserid']){
							$authorName = M('UserInfo')->getFieldByUid($this->uid, 'realname');
							sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=> $authorName . '修改的稿件《' . $article['title'] . '》，请审核！','trans'=>$trans));
						}else{
							$authorName = M('UserInfo')->getFieldByUid($this->uid, 'realname');
							sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=> $authorName . '提交的稿件《' . $article['title'] . '》，请审核！','trans'=>$trans));
						}
						/*删除mysql事件*/
						@M()->execute("DROP EVENT IF EXISTS auto_back_shenhe_{$dataGet['articleId']}");


						$approve=new \Mapi\Model\approveaModel();
						$arr['ip']=I('server.HTTP_X_REAL_IP');
						$arr['author_id']=$this->uid;
						$arr['articleId']=$article['articleId'];
						$arr['state']='提交文稿';
						$arr['time']=time();
						$approve->add($arr);
					}

					$message['resultCode'] = 0;
					$message['message'] = '更新成功';
					$this->ajaxReturn($message);
				} else {
					$message['resultCode'] = 1;
					$message['message'] = '更新失败';
					$this->ajaxReturn($message);
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = '没有权限修改该';
				$this->ajaxReturn($message);
			}
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}
	}

	/**
	 * 根据文稿状态类型获取待查看的提醒
	 * @return [type] [description]
	 */
	public function getWarnList() {
		$waitApprovalTime = I('get.waitTime',time());
		$doingApprovalTime = I('get.doingTime',time());
		$rejectApprovalTime = I('get.rejectTime',time());
		$passApprovalTime = I('get.passTime',time());

		try {
			$model = M('Article');
			$map['user_id'] = $this->uid;
			$map['deletetime']= array('exp', 'is NULL');

			$map['state'] = 0;
			$map['update_time'] = array('gt',$waitApprovalTime);
			$waitApprovalCount = $model->where($map)->count();
			// echo $model->getLastsql();exit;

			$map['state'] = 1;
			$map['update_time'] = array('gt',$passApprovalTime);
			$passApprovalCount = $model->where($map)->count();

			$map['state'] = 2;
			$map['update_time'] = array('gt',$doingApprovalTime);
			$doingApprovalCount = $model->where($map)->count();

			$map['state'] = 3;
			$map['update_time'] = array('gt',$rejectApprovalTime);
			$rejectApprovalCount = $model->where($map)->count();

			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['waitApprovalCount'] = $waitApprovalCount;
			$message['passApprovalCount'] = $passApprovalCount;
			$message['doingApprovalCount'] = $doingApprovalCount;
			$message['rejectApprovalCount'] = $rejectApprovalCount;
			$this->ajaxReturn($message);

		} catch(\Exception $e) {
			$message['resultCode'] = 1;
			$message['message'] = '服务器端异常';
			$this->ajaxReturn($message);
		}

	}

	public function getOwnerArticleList() {
		$status = I('get.status', 4);
		$pageSize = I('get.pageSize', 10);
		$hots = C('UPLOAD_HOST');
		C('VAR_PAGE', 'page');

		$channel = M('Channel')->field('chid, relation')->select();
		$chids = array();
		foreach($channel as $val) {
			$val['relation'] && $val['relation'] = unserialize($val['relation']);
			if(isset($val['relation'][0]) && !empty($val['relation'][0])) {
				if(in_array($this->uid, $val['relation'][0])) {
					$chids[] = $val['chid'];
				}
			}
		}

		// 如果用户有权限则返回待审和待审中的，否则只返回自己的
		if(empty($chids)) {
			switch ($status) {
				case 0:
					$map3['state'] = 0;
					break;
				case 1:
					$map3['state'] = 1;
					break;
				case 2:
					$map3['state'] = 2;
					break;
				case 3:
					$map3['state'] = 3;
					break;
				case 4:
					$map3['state'] = array('neq',-1);
					break;
			}

			$map3['user_id'] = $this->uid;
			$map3['deletetime'] = array('exp', 'is NULL');
		} else {
			switch ($status) { //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
				case 0:
					$map3['state'] = 0;
					break;
				case 1:
					$map3['state'] = 1;
					break;
				case 2:
					$map3['state'] = 2;
					break;
				case 3:
					$map3['state'] = 3;
					break;
				case 4:
					$map3['state'] = array('neq',-1);
					break;

			}

			$map1['column_id'] = array('in', $chids);
			// $map2['_complex'] = $map;
			// $map2['_logic'] = 'AND';

			$map2['user_id'] = $this->uid;
			$map2['_complex'] = $map1;
			$map2['_logic'] = 'OR';

			$map3['deletetime'] = array('exp', 'is NULL');
			$map3['_complex'] = $map2;
			$map3['_logic'] = 'AND';


			// $map3['deletetime'] = array('exp', 'is NULL');
			// $map3['_complex'] = $map2;
			// $map3['_logic'] = 'AND';

			// $map4['state'] = array('neq', '-1');
			// $map4['_complex'] = $map3;
			// $map4['_logic'] = 'AND';
		}

		$model = M('Article');
		$total = $model->where($map3)->count();
		$page = new \Think\Page($total, $pageSize);
		$list = $model->where($map3)->order('create_time desc')->limit($page->firstRow .',' . $page->listRows)->select();
		// echo $model->getLastsql();exit;
		$alist = array();
		$attchment=M('Attachment');
		foreach($list as $key => $val) {
			$alist[$key]['articleId'] = $val['id'];
			$alist[$key]['title'] = $val['title'];
			$alist[$key]['content'] = htmlspecialchars_decode($val['content']);
			$alist[$key]['createTime'] = $val['create_time'];
			$alist[$key]['status'] = $val['state'];
			$a=$attchment->where('type="image" and aid='.$val['id'])->order("sort ASC,attachid ASC")->find();
			if($a){
				$alist[$key]['fileUrl'] =  $a['client_attach_id'] ? C('IMAGE_HOST') . $a['thumb']  : C('UPLOAD_HOST') . $a['thumb'];
				$alist[$key]['isImage'] = 1;
			}else{
				$alist[$key]['fileUrl'] =  '';
				$alist[$key]['isImage'] = 0;
			}
			$b=$attchment->where('type="video" and aid='.$val['id'])->find();
			if($b){
				$alist[$key]['fileUrl'] = $b['client_attach_id'] ? C('IMAGE_HOST') . $b['thumb']  : C('UPLOAD_HOST') . $b['thumb'];//$hots . $b['thumb'] ;
				$alist[$key]['isVideo'] = 1;
			}else{
				$alist[$key]['isVideo'] = 0;
			}

		}

		if($alist) {
			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['articles'] = $alist;
			$this->ajaxReturn($message);
		} else {
			$message['resultCode'] = 0;
			$message['message'] = '未找到记录';
			$message['articles'] = array();
			$this->ajaxReturn($message);
		}
	}


	/**
	 * 删除文稿
	 * @return [type] [description]
	 */
	public function delArticle() {
		apigetpost();
		$articleId = I('post.articleId');

		if(!$articleId) {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}

		$res = M('Article')->where(array('id' => $articleId, 'user_id' => $this->uid,	'state'=>array('in','-1,0,3')))->save(array('deletetime' => time(),'update_time'=>time()));//-1:撤回文稿，3：打回文稿
		if($res) {
			$imgs = M('Attachment')->where(array('aid' => $articleId, 'user_id' => $this->uid))->save(array('aid' => 0));
			$message['resultCode'] = 0;
			$message['message'] = '删除成功';
			$this->ajaxReturn($message);
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '删除失败';
			$this->ajaxReturn($message);

		}
	}

	public function editArticle(){
		$this->revocationArticle(1);
	}

	/**
	 * 撤销文稿
	 * @return [type] [description]
	 */
	public function revocationArticle($flag=0) { //$flag：1-点的修改按钮   0-点的撤回按钮
		apigetpost();
		$articleId = I('post.articleId');
		if(!$articleId) {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}

		$map['id']=$articleId;
		$article=M('Article')
			->alias('ar')
			->join('__CHANNEL__ ch ON ar.column_id=ch.chid','left')
			->field("user_id createuserid,id articleId,state status,relation, title")
			->where($map)->find();

		if($article){
			$approve = unserialize($article['relation']);
			if($article['createuserid']==$this->uid ||  in_array($this->uid,$approve[0])){

				// $res = M('Article')->where(array('id' => $articleId, 'user_id' => $this->uid))->save(array('state' => -1,'update_time'=>time()));
				$res = M('Article')->where(array('id' => $articleId))->save(array('state' => -1,'update_time'=>time()));

				if($res !== false) {


					switch ($flag) {
						case 0: //点的撤销按钮
							$channel = unserialize($article['relation']);
							$uidList = $channel[0];
							$authorName = M('UserInfo')->where(array('uid' => $article['createuserid']))->getField('realname');
							$trans=json_encode(array('pushCode'=>101,'objectId'=>$articleId,'userId'=>0));
							sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>$authorName.'发布的《' . $article['title'] . '》稿件已经被作者撤回。','trans'=>$trans));
							break;

						case 1: //点的修改按钮
							if($this->uid!=$article['createuserid']){
								/*
								审核人员点击修改后，10分钟后自动释放
								 */
								@M()->execute("CREATE  EVENT IF NOT EXISTS auto_back_shenhe_{$articleId} ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL ".C('Back_shenhe_time')." MINUTE   DO UPDATE whtvjw_article SET state=0 WHERE id={$articleId} AND state=-1");
							}

							if(in_array($this->uid,$approve[0])) {
								$channel = unserialize($article['relation']);
								$uidList = $channel[0];
								//$uidList[] = $article['user_id'];
								$uidList=array_unique($uidList);
								foreach ($uidList as $key => $value) {
									if($value==$this->uid || $value==$article['createuserid']){
										unset($uidList[$key]);
									}
								}

								$trans=json_encode(array('pushCode'=>101,'objectId'=>$articleId,'userId'=>0));
								$currentUserName = M('UserInfo')->where(array('uid' => $this->uid))->getField('realname');

								sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $article['title'] . '》稿件正在被' . $currentUserName . '修改，请稍后。','trans'=>$trans));

								if($article['createuserid']!=$this->uid){
									sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$article['createuserid'],'title'=>'见微','content'=>'您的稿件《' . $article['title'] . '》正在被' . $currentUserName . '修改，请稍后。','trans'=>$trans));
								}
							}
							break;
					}

					$message['resultCode'] = 0;
					$message['message'] = '撤销成功';
					$approve=new \Mapi\Model\approveaModel();
					$arr['ip']=I('server.HTTP_X_REAL_IP');
					$arr['author_id']=$this->uid;
					$arr['articleId']=$articleId;
					$arr['state']='撤销文稿';
					$arr['time']=time();
					$approve->add($arr);

					$this->ajaxReturn($message);
				} else {
					$message['resultCode'] = 1;
					$message['message'] = '撤销失败';
					$this->ajaxReturn($message);
				}
			} else {
				$message['resultCode'] = 1;
				$message['message'] = '没有权限修改';
				$this->ajaxReturn($message);
			}
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}
	}

	public function unRevocationArticle() {
		apigetpost();
		$articleId = I('post.articleId');
		if(!$articleId) {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}

		$map['id']=$articleId;
		$article=M('Article')
			->alias('ar')
			->join('__CHANNEL__ ch ON ar.column_id=ch.chid','left')
			->field("user_id createuserid,id articleId,state status,relation, ar.column_id chid, ar.title")
			->where($map)->find();

		if($article){
			$approve = unserialize($article['relation']);
			if($article['createuserid']==$this->uid ||  in_array($this->uid,$approve[0])){

				$res = M('Article')->where(array('id' => $articleId))->save(array('state' => 0,'create_time'=>time(), 'update_time' => time()));

				if($res !== false) {

					/*消息推送*/
					$trans=json_encode(array('pushCode'=>100,'objectId'=>$articleId,'userId'=>0));
					$channelid = unserialize($article['relation']);
					$uidList = $channelid[0];
					foreach ($uidList as $key => $value) {
						if($value==$this->uid){
							unset($uidList[$key]);
						}
					}

					if($this->uid!=$article['createuserid']){
						$authorName = M('UserInfo')->getFieldByUid($this->uid, 'realname');
						sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=> $authorName . '修改的稿件《' . $article['title'] . '》，请审核！','trans'=>$trans));
					}else{
						$authorName = M('UserInfo')->getFieldByUid($this->uid, 'realname');
						sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=> $authorName . '提交的稿件《' . $article['title'] . '》，请审核！','trans'=>$trans));
					}

					@M()->execute("DROP EVENT IF EXISTS auto_back_shenhe_{$articleId}");

					$message['resultCode'] = 0;
					$message['message'] = '设置成功';
					/*$approve=new \Mapi\Model\approveaModel();
					$arr['ip']=I('server.HTTP_X_REAL_IP');
					$arr['author_id']=$this->uid;
					$arr['articleId']=$articleId;
					$arr['state']='提交文稿';
					$arr['time']=time();
					$approve->add($arr);*/
					$this->ajaxReturn($message);
				} else {
					$message['resultCode'] = 1;
					$message['message'] = '设置失败';
					$this->ajaxReturn($message);
				}
			} else {
				$message['resultCode'] = 1;
				$message['message'] = '没有权限修改';
				$this->ajaxReturn($message);
			}
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}
	}


	protected function changeArticleStateByState($articleId,$orgi_state,$new_state){
		$data['state']=$new_state;
		$data['update_time']=time();

		$re=M('Article')->where(array(
			'id'=>$articleId,
			'state'=>$orgi_state
		))->save($data);
		return ($re);
	}

	public function articleInfo(){
		// $userToken= I('get.userToken');	 //是	String	   用户登录的唯一标识
		$articleId=I('get.articleId');  //是      int         文稿id
		$author_id=$this->uid;	//用户ID

		$hots=C('UPLOAD_HOST');
		if($author_id){
			if($articleId){
				$map['id']=$articleId;
				$article=M('Article')
					->alias('ar')
					->join('__CHANNEL__ ch ON ar.column_id=ch.chid','left')
					->field("user_id createuserid,id articleId,title,verify_id,content,create_time createTime ,author reporters,state status,relation")
					->where($map)->find();

				if($article){
					$approve=unserialize($article['relation']);
					if($article['createuserid']==$author_id ||  (isset($approve[0]) && in_array($author_id,$approve[0]))){
						if(in_array($author_id,$approve[0])){
							$article['isApprove']=1;
							//点击详情修改文稿状态
							$res=$this->changeArticleStateByState($articleId,0,2);

							if($res){
								$article['status']='2';
								$approve=new \Mapi\Model\approveaModel();
								$arr['ip']=I('server.HTTP_X_REAL_IP');
								$arr['author_id']=$author_id;
								$arr['articleId']=$articleId;
								$arr['state']='审核中';
								$arr['time']=time();
								$approve->add($arr);
							}
						}else{
							$article['isApprove']=0;
						}
						unset($article['relation']);
					}else{
						$article=array();
						$message['resultCode']="0";
						$message['message']="";
						$message['article']=$article;
						$this->ajaxReturn($message);
						exit();
					}

//					$attchment=M('Attachment')->field("attachid fileId,client_attach_id clientAttachId,CONCAT('{$hots}',filepath,filename) url,type fileType,sort,CONCAT('{$hots}',thumb) thumb,thumbwidth,thumbheight,CONCAT(filesize,sort) fileinfo,audiosecondcount")
//						->order('sort ASC,uploadtime DESC')
//						->where(array('aid'=>$articleId, 'attachstate' => 1))->select();

					$attchment=M('Attachment')->field("attachid fileId,client_attach_id clientattachid,CONCAT(filepath,filename) url,type fileType,sort,thumb,thumbwidth,thumbheight,CONCAT(filesize,sort) fileinfo,audiosecondcount")
						->order('sort ASC,uploadtime DESC')
						->where(array('aid'=>$articleId, 'attachstate' => 1))->select();

					foreach($attchment as $k=>$v){
						$attchment[$k]['fileType']=$v['filetype'];
						$attchment[$k]['thumbWidth']=$v['thumbwidth'] ? $v['thumbwidth'] : '';
						$attchment[$k]['thumbHeight']=$v['thumbheight'] ? $v['thumbheight'] : '';
						$attchment[$k]['thumb']=$v['thumb'] ? ($v['clientattachid'] ? C('IMAGE_HOST') . $v['thumb'] : C('UPLOAD_HOST') . $v['thumb']) : '';
						$attchment[$k]['url'] = $v['clientattachid'] ? C('IMAGE_HOST') . $v['url'] : C('UPLOAD_HOST') . $v['url'];
						$attchment[$k]['audiosecondcount']=$v['audiosecondcount'] ? $v['audiosecondcount'] : 0;

						unset($attchment[$k]['filetype']);
						unset($attchment[$k]['thumbwidth']);
						unset($attchment[$k]['thumbheight']);
					}

					$article['fileArray']= $attchment;
					if($article['reporters']){
						$map['uid']=array("in",$article['reporters']);
						$reporters=M('UserInfo')->field("uid,realname")->where($map)->select();
						$article['reportersIdAndNames']=$reporters;
					}else{
						$article['reportersIdAndNames']=array();
					}

					array_unshift($article['reportersIdAndNames'], array(
						'uid' =>  $article['createuserid'],
						'realname' => M('UserInfo')->where(array('uid' => $article['createuserid']))->getField('realname'),
					));

					$article['reportersIdAndNames'] = $this->unique_arr($article['reportersIdAndNames'],false);

					$reporters = explode(',', $article['reporters']);
					if(!in_array($article['createuserid'], $reporters)) {
						$article['reporters'] = $article['reporters'] ? $article['reporters'] . ',' . $article['createuserid'] : $article['createuserid'];
					}

				}


				if($article['status'] == 1) {
					$article['approver'] = M('UserInfo')->where(array('uid' => $article['verify_id']))->getField('realname');
				} elseif($article['status'] == 3) {
					$article['approver'] = M('UserInfo')->where(array('uid' => $article['verify_id']))->getField('realname');
					$info = M('ReturnReason')->field('details')
						->where(array('article_id' => $articleId))->order('reason_id desc')->find();
					$article['reason'] = $info['details'];
				}

				$message['resultCode']="0";
				$message['message']="";
				$message['article']=$article;
			}else{
				$message['resultCode']="1";
				$message['message']='文稿ID未知';
			}
		}else{
			$message['resultCode']="1";
			$message['message']='用户未登录';
		}
		//dump($message);
		$this->ajaxReturn($message);
	}


	protected function unique_arr($array2D,$stkeep=false,$ndformat=true)
	{
		// 判断是否保留一级数组键 (一级数组键可以为非数字)
		if($stkeep) $stArr = array_keys($array2D);

		// 判断是否保留二级数组键 (所有二级数组键必须相同)
		if($ndformat) $ndArr = array_keys(end($array2D));

		//降维,也可以用implode,将一维数组转换为用逗号连接的字符串
		foreach ($array2D as $v){
			$v = join(",",$v);
			$temp[] = $v;
		}

		//去掉重复的字符串,也就是重复的一维数组
		$temp = array_unique($temp);

		//再将拆开的数组重新组装
		foreach ($temp as $k => $v)
		{
			if($stkeep) $k = $stArr[$k];
			if($ndformat)
			{
				$tempArr = explode(",",$v);
				foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval;
			}
			else $output[$k] = explode(",",$v);
		}

		$arr=array();
		foreach ($output as $key => $value) {
			$arr[]=$value;
		}
		return $arr;
	}


	/*    function untreadArticle(){
            $userToken= I('get.userToken');  //是    String     用户登录的唯一标识
            $articleId=I('get.articleId');  //是      int         文稿id
            $author_id=F($userToken);   //用户ID
            if($author_id){
                if($articleId){
                    $data['state']=3; //3-退回文稿
                    $re=M('Article')->where(array(
                        'user_id'=>$author_id,
                        'id'=>$articleId
                    ))->save($data);
                    if($re){
                        $message['resultCode']="0";
                        $message['message']='成功处理';
                    }else{
                        $message['resultCode']="-1";
                        $message['message']='服务器错误';
                    }

                }else{
                    $message['resultCode']="1";
                    $message['message']='文稿ID未知';
                }
            }else{
                $message['resultCode']="1";
                $message['message']='用户未登录';
            }
            $this->ajaxReturn($message);
        }*/


	/* public function approveArticle(){

         apigetpost();

         // $userToken= I('post.userToken');  //是    String     用户登录的唯一标识
         $articleId=I('post.articleId');  //是      int         文稿id
         $state=I('post.status');       //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
         $strArr=array('待审核','审核通过','审核中','退稿');
         $author_id=$this->uid;   //用户ID
         if($author_id){
             if($articleId){
                 if(isset($state) && in_array($state,array(0,1,2,3))){
                     $ar=$this->getArticleInfo($articleId);
                     if(in_array($author_id,$ar['relation'][0])){
                         if($state == 3) {
                             $reason = I('post.reason', '');
                             if($reason) {
                                 $arr['details'] = $reason;
                                 $arr['article_id'] = $articleId;
                                 $arr['details'] = $reason;
                                 $arr['createtime'] = time();
                                 M('ReturnReason')->add($arr);
                             }
                         }
                         $data['state']=$state;
                         if(!in_array($state,array(1,3))) {
                             $data['update_time']=time();
                         }
                               $data['verify_id'] = $this->uid;
                         $re=M('Article')->where(array(
                             'id'=>$articleId
                         ))->save($data);
                         if($re){
                             if($state==1){
                                 $this->pushArticle($articleId); //审核通过后向M2O后台推送见微文稿

                             }
                             $message['resultCode']="0";
                             $message['message']="已设置为：".$strArr[$state];
                             $approve=new \Mapi\Model\approveaModel();
                             $arr['ip']=I('server.HTTP_X_REAL_IP');
                             $arr['author_id']=$author_id;
                             $arr['articleId']=$articleId;
                             $arr['state']=$strArr[$state];
                             $arr['time']=time();
                             $approve->add($arr);
                         }else{
                             $message['resultCode']="-1";
                             $message['message']='服务器错误';
                         }
                     }else{
                         $message['resultCode']="1";
                         $message['message']='您不具有审核此文稿权限';
                     }
                 }else{
                     $message['resultCode']="1";
                     $message['message']='未知的审核操作';
                 }
             }else{
                 $message['resultCode']="1";
                 $message['message']='文稿ID未知';
             }
         }else{
             $message['resultCode']="1";
             $message['message']='用户未登录';
         }
         $this->ajaxReturn($message);
     }*/


	/**
	 * 只能操作待审核和审核中,注释时间：2016/8/9，注释原因：与unRevocationArticle功能重复
	 * @return [type] [description]
	 */
	/**public function approveArticle(){

	apigetpost();

	// $userToken= I('post.userToken');  //是    String     用户登录的唯一标识
	$articleId=I('post.articleId');  //是      int         文稿id
	$state=I('post.status');       //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
	$strArr=array(0 => '待审核', 2 => '审核中');
	// $strArr=array(0 => '待审核');
	$author_id=$this->uid;   //用户ID
	if($author_id){
	if($articleId){
	if(isset($state) && in_array($state,array(0,2))){
	$ar=$this->getArticleInfo($articleId);
	if(in_array($author_id,$ar['relation'][0])){
	$data['state']=$state;
	$data['update_time'] = time();
	$re=M('Article')->where(array(
	'id'=>$articleId
	))->save($data);
	if($re){
	$message['resultCode']="0";
	$message['message']="已设置为：".$strArr[$state];
	$approve=new \Mapi\Model\approveaModel();
	$arr['ip']=I('server.HTTP_X_REAL_IP');
	$arr['author_id']=$author_id;
	$arr['articleId']=$articleId;
	$arr['state']=$strArr[$state];
	$arr['time']=time();
	$approve->add($arr);

	}else{
	$message['resultCode']="-1";
	$message['message']='服务器错误';
	}
	}else{
	$message['resultCode']="1";
	$message['message']='您不具有审核此文稿权限';
	}
	}else{
	$message['resultCode']="1";
	$message['message']='未知的审核操作';
	}
	}else{
	$message['resultCode']="1";
	$message['message']='文稿ID未知';
	}
	}else{
	$message['resultCode']="1";
	$message['message']='用户未登录';
	}
	$this->ajaxReturn($message);
	}**/

	/**
	 * 只能操作待审核，为了兼容老版本的用户
	 * @return [type] [description]
	 */
	public function approveArticle(){
		$this->unRevocationArticle();
	}

	/**
	 * 通过审核
	 * @return [type] [description]
	 */
	public function passArticle(){

		apigetpost();

		// $userToken= I('post.userToken');  //是    String     用户登录的唯一标识
		$articleId=I('post.articleId');  //是      int         文稿id
		$state=I('post.status');       //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
		$author_id=$this->uid;   //用户ID
		if($author_id){
			if($articleId){
				if(isset($state) && $state == 1){
					$ar=$this->getArticleInfo($articleId);
					if(in_array($author_id,$ar['relation'][0])){
						$data['state']=$state;
						$data['update_time']=time();
						$data['verify_id'] = $this->uid;
						$re=M('Article')->where(array('id'=>$articleId))->save($data);
						if($re){
							if($state==1){
								//$this->pushArticle($articleId); //审核通过后向M2O后台推送见微文稿

								$ainfo = M('Article')->where(array('id' => $articleId))->find();
								// $verifyName = M('UserInfo')->where(array('uid' => $ainfo['verify_id']))->getField('realname'); // 审核人姓名


								$relation = M('Channel')->where(array('chid' => $ainfo['column_id']))->getField('relation');
								$relation = unserialize($relation);
								$uidList = $relation[0];
								// $uidlist[] = $ainfo['user_id'];
								$uidList = array_unique($uidList);
								foreach($uidList as $k => $v) {
									if($v == $this->uid)
										unset($uidList[$k]);
								}

								$trans=json_encode(array('pushCode'=>100,'objectId'=>$articleId,'userId'=>0));
								sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $ainfo['title'] . '》稿件通过审核','trans'=>$trans));

								if($ainfo['user_id'] != $ainfo['verify_id']  && !in_array($ainfo['user_id'],$uidList)) {
									sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$ainfo['user_id'],'title'=>'见微','content'=>'您的稿件《' . $ainfo['title'] . '》已经通过审核','trans'=>$trans));
								}

								$attach = M('Attachment')->field('client_attach_id')->where(array('aid' => $articleId))->find();
								if($attach['client_attach_id']) {
									sock_get('http://localhost/Mapi/push/pushArticle.html',array('articleId'=>$articleId));
								} else {
									sock_get('http://localhost/Mapi/push/pushArticleByLocal.html',array('articleId'=>$articleId));
								}


							}
							$message['resultCode']="0";
							$message['message']="已设置为：通过审核";
							/*$approve=new \Mapi\Model\approveaModel();
							$arr['ip']=I('server.HTTP_X_REAL_IP');
							$arr['author_id']=$author_id;
							$arr['articleId']=$articleId;
							$arr['state']="通过审核";
							$arr['time']=time();
							$approve->add($arr);*/
							
						}else{
							$message['resultCode']="-1";
							$message['message']='服务器错误';
						}
					}else{
						$message['resultCode']="1";
						$message['message']='您不具有审核此文稿权限';
					}
				}else{
					$message['resultCode']="1";
					$message['message']='未知的审核操作';
				}
			}else{
				$message['resultCode']="1";
				$message['message']='文稿ID未知';
			}
		}else{
			$message['resultCode']="1";
			$message['message']='用户未登录';
		}
		$this->ajaxReturn($message);
	}


	/**
	 * 退稿
	 * @return [type] [description]
	 */
	public function returnedArticle(){

		apigetpost();

		// $userToken= I('post.userToken');  //是    String     用户登录的唯一标识
		$articleId=I('post.articleId');  //是      int         文稿id
		$state=I('post.status');       //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
		$author_id=$this->uid;   //用户ID
		$reason = I('post.reason', '');
		if($author_id){
			if($articleId){
				if(isset($state) && $state == 3){
					if($reason) {
						$ar=$this->getArticleInfo($articleId);
						if(in_array($author_id,$ar['relation'][0])){
							$data['state']=$state;
							$data['update_time']=time();
							$data['verify_id'] = $this->uid;
							$re=M('Article')->where(array(
								'id'=>$articleId
							))->save($data);
							if($re){
								$arr['details'] = $reason;
								$arr['article_id'] = $articleId;
								$arr['details'] = $reason;
								$arr['user_id'] = $author_id;
								$arr['createtime'] = time();
								$r = M('ReturnReason')->add($arr);
								if(!$r) {
									$message['resultCode']="0";
									$message['message']="退稿原因写入失败";
									$this->ajaxReturn($message);
								}


								$userid = $ar['user_id'];
								$uidList = $ar['relation'][0];

								foreach($uidList as $k=>$v){
									if($v==$this->uid){
										unset($uidList[$k]);
									}
								}

								$trans=json_encode(array('pushCode'=>100,'objectId'=>$articleId,'userId'=>0));

								if($ar['verify_id'] != $userid && !in_array($userid,$uidList)) {
									sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$userid,'title'=>'见微','content'=> '您的稿件《' . $ar['title'] . '》审核未通过，已退稿','trans'=>$trans));
								}

								//$trans=json_encode(array('pushCode'=>101,'objectId'=>$articleId,'userId'=>0));
								sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $ar['title'] . '》稿件审核未通过，已退稿','trans'=>$trans));


								$message['resultCode']="0";
								$message['message']="已设置为：退稿";
								$approve=new \Mapi\Model\approveaModel();
								$arr['ip']=I('server.HTTP_X_REAL_IP');
								$arr['author_id']=$author_id;
								$arr['articleId']=$articleId;
								$arr['state']='退稿';
								$arr['time']=time();
								$approve->add($arr);

							}else{
								$message['resultCode']="-1";
								$message['message']='服务器错误';
							}
						}else{
							$message['resultCode']="1";
							$message['message']='您不具有审核此文稿权限';
						}
					} else {
						$message['resultCode']="1";
						$message['message']="未填写退稿原因";
					}
				}else{
					$message['resultCode']="1";
					$message['message']='未知的审核操作';
				}
			}else{
				$message['resultCode']="1";
				$message['message']='文稿ID未知';
			}
		}else{
			$message['resultCode']="1";
			$message['message']='用户未登录';
		}
		$this->ajaxReturn($message);
	}


	/**
	 * 获取退稿原因
	 * @return [type] [description]
	 */
	public function getReasonByArticleId() {
		apigetpost();
		$articleId = I('post.articleId');
		if($articleId) {
			$info = M('ReturnReason')->where(array('article_id' => $articleId))->select();
			if(!empty($info)) {
				$message['data'] = $info;
				$message['resultCode'] = "0";
				$message['message'] = '';
			} else {
				$message['resultCode'] = "1";
				$message['message'] = '暂无记录';
			}
		} else {
			$message['resultCode'] = "1";
			$message['message'] = '稿件不存在';
		}
		$this->ajaxReturn($message);
	}


	protected function getArticleInfo($id){
		$article=M('Article')
			->alias('ar')
			->join('__CHANNEL__ ch ON ar.column_id=ch.chid','left')
			->where(array(
				'id'=>$id
			))->find();
		if($article){
			$approve=unserialize($article['relation']);
			$article['relation']=$approve;
		}
		return $article;
	}



	function sock_post($url, $data)
	{

		$query_str = http_build_query($data);

		$info = parse_url($url);
		$fp = fsockopen($info["host"], 10085, $errno, $errstr, 3);
		$head = "GET ".$info['path']."?".$query_str." HTTP/1.0\r\n";
		$head .= "Host: ".$info['host']."\r\n";
		$head .= "\r\n";
		$write = fputs($fp, $head);
		fclose($fp);
	}

	/**
	 * 获取文稿的状态
	 * @return [type] [description]
	 */
	public function getArticleState() {
		$articleId = I('get.articleId');
		if($articleId) {
			$state = M('Article')->getFieldById($articleId, 'state');

			$message['resultCode'] = "0";
			$message['message'] = '';
			$message['state'] = $state;

		} else {
			$message['resultCode'] = "1";
			$message['message'] = '文稿ID未知';
		}

		$this->ajaxReturn($message);
	}


	/**
	 * 获取文稿附件队列信息
	 * @return [type] [description]
	 */
	public function  setAttachmentState(){
		apigetpost();
		$articleId=I('post.articleId');
		$attchment=I('post.attchmentInfo');
		if($articleId){
			if($attchment){
				$attchment=explode(',',$attchment);
				M()->startTrans();
				$res=M('Attachment')->where(array('aid'=>$articleId))->save(array('attachstate'=>0));
				if($res){
					foreach($attchment as $value){
						$attchinfo=explode('_',$value);
						$arr[]=$attchinfo[0];
						$resinfo=M('Attachment')->save(array('attachid'=>$attchinfo[0],'sort'=>$attchinfo[1],'attachstate'=>1));
						if(!$resinfo){
							M()->rollback();
							$message['resultCode'] = -1;
							$message['message'] = '服务器端异常';
							$this->ajaxReturn($message);
						}
					}
					M()->commit();
					$str=gethttpcurl('http://localhost:81/'.U('unRevocationArticle'),array('postarr'=>array('articleId'=>$articleId)),I('server.HTTP_USERTOKEN'));
					$message=json_decode($str,true);
					// \Think\Log::write($str,'WARN11111');
				}else{
					M()->rollback();
					$message['resultCode'] = -1;
					$message['message'] = '服务器端异常';
				}
			}else{
				$message['resultCode'] = 1;
				$message['message'] = '附件状态未知';
			}

		}else{
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
		}

		$this->ajaxReturn($message);
	}

	public function autoLoadToken() {
	    // 七牛对象存储的上传凭证
        $putPolicy=array(
            'saveKey'=>'article/$(etag)',
            'callbackUrl'=>"http://".I("server.HTTP_HOST").':'.C('HOST_PORT').'/Mapi/Article/qiniuCallBack',
            'callbackHost'=>I("server.HTTP_HOST").':'.C('HOST_PORT'),
            'callbackBody'=>'clientAttachId=$(x:clientAttachId)&rotate=$(x:rotate)&articleId=$(x:articleId)&fsize=$(fsize)&key=$(key)&ext=$(ext)&hash=$(etag)&image=$(imageInfo)&avinfo=$(avinfo)',
        );
        $upAuth = new Auth(C('QINIU_accessKey'), C('QINIU_secretKey'));
        $bucket = C('QINIU_BUCKET');
        $uploadToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);

		$message['resultCode'] = 0;
		$message['message'] = '';
		$message['token'] = $uploadToken;

		$this->ajaxReturn($message);
	}

	/**
	 * 上传图片的token
	 * @return [type] [description]
	 */
	public function videoLoadToken() {
	    // 七牛对象存储的上传凭证
        $putPolicy=array(
            'saveKey'=>'article/$(etag)',
            'persistentOps'=>"vframe/jpg/offset/1|saveas/" .\Qiniu\base64_urlSafeEncode(C('QINIU_BUCKET') . ":$(key).jpg"),
            'persistentPipeline' => 'jwtrain3',
            // 'persistentNotifyUrl' => 'http://'.I("server.HTTP_HOST").'/Mapi/Article/qiniuPersistentCallBack',
            'returnBody'=>'clientAttachId=$(x:clientAttachId)&articleId=$(x:articleId)&fsize=$(fsize)&key=$(key)&hash=$(etag)&image=$(imageInfo)&avinfo=$(avinfo)&persistentId=$(persistentId)',
        );
        $upAuth = new Auth(C('QINIU_accessKey'), C('QINIU_secretKey'));
        $bucket = C('QINIU_BUCKET');
        $uploadToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);

		$message['resultCode'] = 0;
		$message['message'] = '';
		$message['token'] = $uploadToken;

		$this->ajaxReturn($message);
	}


	public function qiniuCallBack(){
		apigetpost();

		if(I('post.avinfo') || I('post.image')) {
	        $_POST['image']=json_decode($_POST['image'],true);
	        $_POST['avinfo']=json_decode($_POST['avinfo'],true);
	        $image_info=I('post.image');
	        $av_info=I('post.avinfo');
	        $data['aid']=I("post.articleId");
	        $data['client_attach_id']=I("post.clientAttachId");
	        $data['filename']=I("post.hash");
	        $data['filepath']=str_replace(I("post.hash"),"",I("post.key"));
	        $data['filesize']=formatBytes(I("post.fsize"));
	        $data['ext']=I("post.ext");
			$rotate = I('post.rotate');

	        if($image_info){
	            $data['type']="image";
	            $data['thumbwidth']=$data['oriwidth']=$image_info['width'];
	            $data['thumbheight']=$data['oriheight']=$image_info['height'];
	            $data['thumb']=I("post.key");
	        }else if($av_info['audio'] && $av_info['video']){
	            $data['type']="video";
	            //根据视频的是否旋转，判断原始宽高
/*	            if(!isset($av_info['video']['tags']['rotate']) || $av_info['video']['tags']['rotate']==0 || $av_info['video']['tags']['rotate']==180){
	                $data['oriwidth']=$av_info['video']['width'];
	                $data['oriheight']=$av_info['video']['height'];
	            }else{
	                $data['oriwidth']=$av_info['video']['height'];
	                $data['oriheight']=$av_info['video']['width'];
	            }*/
				if($rotate == 0 || $rotate == 180) {
					$data['oriwidth']=$av_info['video']['width'];
					$data['oriheight']=$av_info['video']['height'];
				} elseif($rotate == 90 || $rotate == 270) {
					$data['oriwidth']=$av_info['video']['height'];
					$data['oriheight']=$av_info['video']['width'];
				}
	        }else if($av_info['audio']){
	            $data['type']="audio";
	            $data['audiosecondcount']=round($av_info['format']['duration']);
	        }
	        $data['uploadtime']=time();
	        $attachid=M('attachment')->add($data);

	        if($attachid) {
		        if($data['type']=="video"){
	            	$this->vframeQiniu($data['filepath'] . $data['filename'],$data['oriwidth'],$data['oriheight'],$attachid);
	        	}
	        	$this->ajaxReturn(array('success' => true, 'attachid' => $attachid));
	        }
		}
	}


    public function  setQiniuAttachmentState(){
        apigetpost();
        $articleId=I('post.articleId');
        $attchment=I('post.attchmentInfo');
        if($articleId){
            if($attchment){
                $attchment=explode(',',$attchment);
                M()->startTrans();
                $res=M('Attachment')->where(array('aid'=>$articleId))->save(array('attachstate'=>0));
                if($res){
                    foreach($attchment as $value){
                        $attchinfo=explode('_',$value);
                        $arr[]=$attchinfo[0];
                        $resinfo=M('Attachment')->where(array("client_attach_id"=>$attchinfo[0]))->save(array('sort'=>$attchinfo[1],'attachstate'=>1));
                        if(!$resinfo){
                            M()->rollback();
                            $message['resultCode'] = -1;
                            $message['message'] = '服务器端异常';
                            $this->ajaxReturn($message);
                        }
                    }
                    M()->commit();
                    $str=gethttpcurl('http://localhost:81/'.U('unRevocationArticle'),array('postarr'=>array('articleId'=>$articleId)),I('server.HTTP_USERTOKEN'));
                    $message=json_decode($str,true);
                    // \Think\Log::write($str,'WARN11111');
                }else{
                    M()->rollback();
                    $message['resultCode'] = -1;
                    $message['message'] = '服务器端异常';
                }
            }else{
                $message['resultCode'] = 1;
                $message['message'] = '附件状态未知';
            }

        }else{
            $message['resultCode'] = 1;
            $message['message'] = '文稿ID未知';
        }

        $this->ajaxReturn($message);
    }

    public function vframeQiniu($key,$w,$h,$attachid){
        $accessKey = C('QINIU_accessKey');
        $secretKey = C('QINIU_secretKey');
        $bucket = C('QINIU_BUCKET');
        $auth = new Auth($accessKey, $secretKey);
        //转码是使用的队列名称。 https://portal.qiniu.com/mps/pipeline
        $pipeline = 'C3DQg0Yz'; //
        //转码完成后通知到你的业务服务器。
        $notifyUrl = "http://".I("server.HTTP_HOST").":".C('HOST_PORT').'/Mapi/Article/setQiniuVideoThumb/attachid/'.$attachid;
        $force = false;

        $config = new \Qiniu\Config();
        $config->useHTTPS = true;
        $pfop = new PersistentFop($auth, $config);

        //要进行视频截图操作
        $h=round($h*345/$w);
        $fops = "vframe/jpg/offset/1/w/345/h/".$h."|saveas/" .\Qiniu\base64_urlSafeEncode($bucket . ":".$key.".jpg");
		//$fops = "vframe/jpg/offset/1/w/".$w."/h/".$h."|saveas/" .\Qiniu\base64_urlSafeEncode($bucket . ":".$key.".jpg");

//		$h=round($h*680/$w);
        M('Attachment')->where(array('attachid'=>$attachid))->save(array('thumbwidth'=>345,'thumbheight'=>$h));
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);
        if($err != null) {
        	return array('success' => false);
        } else {
        	return array('success' => true);
        }
    }

    public function setQiniuVideoThumb($attachid){

        apigetpost();
        $key=I("post.");
        if($key['code'].""==="0"){
            M('Attachment')->where(array('attachid'=>$attachid))->save(array('thumb'=>$key['inputKey'].".jpg"));
        }


    }
}